package com.study.system.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.study.system.entity.Course;
import com.study.system.entity.ElasticsearchEntity;
import com.study.system.entity.PageEntity;
import com.study.system.search.client.CourseServiceFeignClient;
import com.study.system.search.dao.ElasticsearchDAO;
import com.study.system.search.service.CourseIndexService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 课程索引操作实现类
 */
@Service
public class CourseIndexServiceImpl implements CourseIndexService {

    public static final String INDEX_NAME = "course";

    @Resource
    private ElasticsearchDAO dao;

    @Resource
    private CourseServiceFeignClient client;

    @Override
    public void initCourseIndex() throws IOException {
        //判断课程索引是否存在
        if(dao.existsIndex(INDEX_NAME)){
            //存在就删除
            dao.deleteIndex(INDEX_NAME);
        }
        //创建索引
        dao.createIndex(INDEX_NAME);
        //调用课程微服务获得所有课程
        List<Course> courses = client.getAllCourses().getBody();
        //添加数据到ES实体类集合中
        List<ElasticsearchEntity> entities = new ArrayList<>();
        courses.forEach(course -> {
            entities.add(new ElasticsearchEntity((int) course.getId(),course));
        });
        //批量插入ES
        dao.insertBatch(INDEX_NAME,entities);
    }

    @Override
    public PageEntity searchCourse(Map<String, String> map) throws IOException {
        //把前端json转换为map集合，再从map集合中读取分页、查询条件、排序方式等
        long current = 0,size = 0;
        if(StringUtils.hasText(map.get("current"))){
            current = Long.parseLong(map.get("current"));
        }
        if(StringUtils.hasText(map.get("size"))){
            size = Long.parseLong(map.get("size"));
        }
        Map<String,String> search = new HashMap<>();
        if(StringUtils.hasText(map.get("search"))){
            search = JSON.parseObject(map.get("search"), Map.class);
        }
        Map<String,String> sort = new HashMap<>();
        if(StringUtils.hasText(map.get("sort"))){
            sort = JSON.parseObject(map.get("sort"), Map.class);
        }
        //调用ES的搜索方法
        return dao.search(INDEX_NAME,current,size,search,sort,Course.class);
    }

    @Override
    public void saveCourse(Course course) throws IOException {
        dao.saveOrUpdate(INDEX_NAME,new ElasticsearchEntity((int) course.getId(),course));
    }

    @Override
    public void deleteCourse(Integer id) throws IOException {
        dao.deleteById(INDEX_NAME, String.valueOf(id));
    }
}
